//
//  NotesTeacherGetMoneyVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/7/5.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "NotesTeacherGetMoneyVC.h"
#import "MSNumberScrollAnimatedView.h"
#import "NotesTeacherGetMoneyCell.h"
#import "NotesTeacherGetMoneyModel.h"
#import "HNSNProductOrderView.h"
@interface NotesTeacherGetMoneyVC () <UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) IBOutlet UILabel *_Money;

@property (nonatomic, weak) IBOutlet MSNumberScrollAnimatedView *numberAnimatedV;
@property (strong, nonatomic) IBOutlet UITableView *TableView;



/**
 当前页码
 */
@property (nonatomic, assign) NSInteger CurrentPage;
/**
 临时页码
 */
@property (nonatomic, assign) NSInteger TempPage;
/**
 数据存放
 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/**
 提现
 */
@property (strong, nonatomic) IBOutlet UIButton *GetMoney;

@end

@implementation NotesTeacherGetMoneyVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"资金提现";

    // 配置TableView
    [self SetupTableView];

    //提现layer变换
    self.GetMoney.layer.cornerRadius = 5.0f;
    self.GetMoney.layer.masksToBounds = YES;
    self.GetMoney.layer.borderColor = [UIColor whiteColor].CGColor;
    self.GetMoney.layer.borderWidth = 1.f;
}



#pragma mark  - 配置
/**
 配置TableView
 */
- (void)SetupTableView
{
    // 占位
    self.TableView.tableFooterView = [UIView new];
    self.TableView.tableHeaderView = [UIView new];
    // 预注册
    [self.TableView registerNib:[UINib nibWithNibName:[NotesTeacherGetMoneyCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    // 预估高度
    self.TableView.rowHeight = UITableViewAutomaticDimension;
    self.TableView.estimatedRowHeight = 100;
    //默认页码
    self.CurrentPage = 1;
    // 下拉刷新
    self.TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        //取当前页码给临时页码
        self.TempPage = self.CurrentPage;
        //设当前页码为1
        self.CurrentPage = 1;
        //请求
        [self RefreshData];
    }];
    //上拉加载
    self.TableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        //请求
        [self RefreshData];
    }];
    //开始刷新
    [self.TableView.mj_header beginRefreshing];
}


/**
 刷新失败时，判断是否需要从临时页码里取出来给当前页码
 */
- (void)GetPage
{
    if (self.CurrentPage == 1)
    {
        self.CurrentPage = self.TempPage;
    }
}

/**
 结束刷新

 @param Index 0:结束刷新 1:提示没有更多数据 2:tableView数据源更新
 */
- (void)EndRefresh:(NSInteger)Index;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (Index)
        {
            case 0:
            {
                [self.TableView.mj_header endRefreshing];
                [self.TableView.mj_footer endRefreshing];
            }
                break;
            case 1:
            {
                [self.TableView.mj_footer endRefreshingWithNoMoreData];
            }
                break;
            case 2:
            {
                [self.TableView reloadData];
            }
                break;
            default:
                break;
        }
    });
}



#pragma mark - 网络请求
/**
 网络请求
 */
- (void)RefreshData
{

    NSDictionary *Params = @{
                             @"action"      :@"awardOrderList",
                             @"pageNumber"  :@(self.CurrentPage)
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        //结束刷新
        [self EndRefresh:0];
        //判断是否加载成功
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 得到数组
            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 判断
            if (Arr.count == 0)
            {
                // 提示没有更多数据了
                [self EndRefresh:1];
            }
            else
            {
                if (self.CurrentPage == 1)
                {
                    [self.DataArr removeAllObjects];
                }

                // 模型转对象
                [Arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 强转并保存
                    NotesTeacherGetMoneyModel *Model = [NotesTeacherGetMoneyModel HN_ObjectWithKeyValus:(NSDictionary *)obj];
                    // 余额不在列表的数据里，额外给
                    Model.withdrawMoney = Obj[@"t"][@"withdrawMoney"];
                    [self.DataArr addObject:Model];

                    //取出首个模拟加载余额，只赋值一次·
                    if (self.CurrentPage == 1 && idx == 0) {

                        self.SetMoney(Model.withdrawMoney);
                    }
                }];

                //数据请求成功，页码加1
                self.CurrentPage += 1;

                // 通知表单刷新
                [self EndRefresh:2];
            }
        }
        else
        {
            //页码处理
            [self GetPage];
            //显示错误信息
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {

        //结束刷新
        [self EndRefresh:0];
        //页码处理
        [self GetPage];
        //显示错误信息
        [MBProgressHUD showError:NetErr];
    }];
}



#pragma mark - TableView代理
//区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

//Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取对象
    NotesTeacherGetMoneyModel *Model = self.DataArr[indexPath.row];
    // 实例化
    NotesTeacherGetMoneyCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    // 调用点语法
    Cell.Model = Model;

    return Cell;
}

// 单纯只是来秀动画的
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    // 取对象
    NotesTeacherGetMoneyModel *Model = self.DataArr[indexPath.row];
    // 打开详情
    HNSNProductOrderView.GetMoneyModel(Model);
}




#pragma mark - 方法
/**
 设置金额的动画效果，参数NSString为金额
 */
- (instancetype (^)(NSNumber *))SetMoney {

    return ^(NSNumber *Money) {

        self._Money.hidden = YES;
        self.numberAnimatedV.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:38];
        self.numberAnimatedV.textColor = [UIColor whiteColor];
        self.numberAnimatedV.minLength = 2;
        self.numberAnimatedV.number = [NSString stringWithFormat:@"%@", Money];
        [self.numberAnimatedV startAnimation];

        return self;
    };
}



/**
 提现
 */
- (IBAction)WithdrawCash:(UIButton *)sender {

    //每一个的模拟都有余额，取第一个
    HNSNGetMoneyModel *Model = self.DataArr.firstObject;
    //如果金额小于等于0，则不操作
    if ([Model.withdrawMoney floatValue] <= 0) {
        //无金额提示
        [MBProgressHUD showError:@"您没有更多的金额用于提现"];
        return;
    }

    // 弹出确认框
    NSString *Price = [NSString stringWithFormat:@"您将提现￥%@元，是否继续?",Model.withdrawMoney];
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:Price preferredStyle:(UIAlertControllerStyleActionSheet)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"继续" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {

        [MBProgressHUD showHUD];
        NSDictionary *Params = @{
                                 @"action":@"withdrawAward"
                                 };
        [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

            if ([Obj[@"code"] isEqualToNumber:@1000]) {

                [MBProgressHUD showSuccess:@"提现成功!"];
                //将金额置0
                self.SetMoney(@0.0);
            } else {

                [HUD showError:Obj[@"msg"]];
            }
        } Fail:^(NSError *error) {
            
            [HUD showError:NetErr];
        }];
    }]];

    // 放弃
    [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];

}





#pragma mark - Setter
- (NSMutableArray *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

@end
